import sys
import os

'''
Python3
Date: 4 May 2020
Author: Carbon Black TAU - Jared Myers
Exemplar Hashes:
Description: Extracts and decodes TinyPOS/PinkKite ShellCode from Image files
'''
__VERSION__ = '1.0'


def dec(encoded_buffer, key, decoded_sc):
   i = 0
   for x in encoded_buffer:
       if encoded_buffer[i:i+4] == b'\xCF\xCF\xCF\xCF':
           decoded_sc = decoded_sc + encoded_buffer[i::]
           break
       else:
           decoded_sc = decoded_sc + (x ^ key[i % 4]).to_bytes(1, 'little')
           i += 1
   return decoded_sc


def write_file(name, buff):
   out = open(name, "wb")
   out.write(buff)
   out.close()


def main():
   try:
       global filename
       filename = sys.argv[1]

   except IndexError:
       print('ShellCode Extractor v%s\n' % __VERSION__)
       print('Usage:\n %s <image file>' % (sys.argv[0]))
       quit()

   if not os.path.isfile(filename):
       print('[!]File Not Found Try Again')
       quit()
   try:
       data = open(filename, "rb").read()
       offset = data.find(b'\x48\x31\xDB\x48\xC7\xC0')
       sc = data[offset:len(data)]
       print('saving shellcode data to:\t'+filename + ".sc")
       write_file(filename + ".sc", sc)
       key = bytearray(sc[6:10])
       decoded_sc = sc[:60]
       output = dec(sc[60::], key, decoded_sc)
       print('saving decoded shellcode data to:\t' + filename + "_decoded.sc")
       write_file(filename + "_decoded.sc", output)

   except Exception as e:
       print("[!!!] There seems to be a problem")
       print(e)


if __name__ == "__main__":
   main()
